<template>
    <div class="p-2">
        <div class="mb-[10px]" v-show="showSearch">
            <el-card shadow="hover">
                <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="100">
                    <el-form-item label="证书名称" prop="certificateName">
                        <el-input v-model="queryParams.certificateName" placeholder="请输入证书名称" clearable
                            style="width: 200px" @keyup.enter="handleQuery" />
                    </el-form-item>
                    <el-form-item label="所属企业" prop="companyName">
                        <el-input v-model="queryParams.companyName" placeholder="请输入所属企业" clearable style="width: 200px"
                            @keyup.enter="handleQuery" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>
            </el-card>
        </div>
        <el-card shadow="hover">
            <template #header>
                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button type="primary" plain icon="Plus" @click="handleAdd"
                            v-hasPermi="permissionList.add">新增</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
                            v-hasPermi="permissionList.edit">修改</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
                            v-hasPermi="permissionList.remove">
                            删除
                        </el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="warning" plain icon="Download" @click="handleExport"
                            v-hasPermi="permissionList.export">导出</el-button>
                    </el-col>
                    <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
                </el-row>
            </template>

            <el-table v-loading="loading" :data="regisiterList" border @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="证书名称" align="center" prop="certificateName" min-width="200" />
                <el-table-column label="证书编号" align="center" prop="certificateId" min-width="200"
                    show-overflow-tooltip />
                <el-table-column label="所属企业" align="center" prop="companyName" min-width="200" show-overflow-tooltip />
                <el-table-column label="覆盖范围" align="center" prop="coverage" min-width="180" show-overflow-tooltip />
                <el-table-column label="认证日期" align="center" prop="certifyingTime" min-width="180" />
                <el-table-column label="有效期至" align="center" prop="certifyingEndTime" min-width="180" />
                <el-table-column label="认证机构" align="center" prop="certifyingAgencies" min-width="180" />
                <el-table-column label="操作" min-width="250" align="center" class-name="small-padding fixed-width"
                    fixed="right">
                    <template #default="scope">
                        <el-button link type="primary" icon="ZoomIn"
                            @click="handleCertification(scope.row)">查资质</el-button>
                        <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                            v-hasPermi="permissionList.edit">修改</el-button>
                        <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                            v-hasPermi="permissionList.remove">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize" @pagination="getList" />
        </el-card>

        <!-- 添加或修改资质对话框 -->
        <el-dialog :title="dialog.title" v-model="dialog.visible" width="600px" append-to-body>
            <el-form ref="postFormRef" :model="form" :rules="rules" label-width="110px">
                <!-- 自动生成 -->
                <el-form-item label="证书编号" prop="certificateId">
                    <el-input v-model="form.certificateId" placeholder="请输入证书编号" />
                </el-form-item>
                <el-form-item label="证书名称" prop="certificateName">
                    <el-input v-model="form.certificateName" placeholder="请输入证书名称" />
                </el-form-item>
                <el-form-item label="所属企业" prop="companyId">
                    <el-select style="width: 100%;" v-model="form.companyId" placeholder="请选择所属企业">
                        <el-option v-for="item in companyNameList" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="认证机构" prop="certifyingAgencies">
                    <el-input v-model="form.certifyingAgencies" placeholder="请输入认证机构" />
                </el-form-item>
                <el-form-item label="认证日期" prop="certifyingTime">
                    <el-date-picker v-model="form.certifyingTime" value-format="YYYY-MM-DD" type="date"
                        placeholder="请选择认证日期" />
                </el-form-item>
                <el-form-item label="有效期至" prop="certifyingEndTime">
                    <el-date-picker v-model="form.certifyingEndTime" value-format="YYYY-MM-DD" type="date"
                        placeholder="请选择有效期" />
                </el-form-item>
                <el-form-item label="覆盖范围" prop="coverage">
                    <el-input v-model="form.coverage" type="textarea" placeholder="请输入覆盖范围" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="certificationRegisiter">
import { list, add, del, update, getDetail, code, companyName } from "@/api/business/enterprise/certification.js";
import { ElMessage, ElMessageBox } from 'element-plus'
import { toRefs, ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
const { proxy } = getCurrentInstance();
const pageName = "资质信息登记"
// 按钮权限
const permissionList = {
    add: ['business:certification:register:add'],
    edit: ['business:certification:register:edit'],
    remove: ['business:certification:register:remove'],
    export: ['business:certification:register:export']
};
const router = useRouter()
// 中标数据
const regisiterList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const postFormRef = ref();
const queryFormRef = ref();
const companyNameList = ref([])
const dialog = reactive({
    visible: false,
    title: ''
});

const initFormData = {
    idArray: undefined,
    certificateName: '',
    certificateId: '',
    coverage: '',
    certifyingTime: "",
    certifyingAgencies: '',
    companyId: ""
}

const data = reactive({
    form: { ...initFormData },
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        certificateName: '',
        companyName: '',
    },
    rules: {
        certificateName: [{ required: true, message: "证书名称不能为空", trigger: "blur" }],
        certifyingAgencies: [{ required: true, message: "认证机构不能为空", trigger: "blur" }],
        companyName: [{ required: true, message: "所属企业不能为空", trigger: "change" }],
        coverage: [{ required: true, message: "覆盖范围不能为空", trigger: "blur" }],
        certificateId: [{ required: true, message: "证书编号不能为空", trigger: "blur" }],
        certifyingEndTime: [{ required: true, message: "有效期至不能为空", trigger: "blur" }],
        certifyingTime: [{ required: true, message: "认证日期不能为空", trigger: "change" }],
    }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询资质列表 */
const getList = async () => {
    loading.value = true;
    const res = await list(queryParams.value);
    regisiterList.value = res.rows;
    total.value = res.total;
    loading.value = false;
}
/** 查询资质方法 */
const handleCertification = (row) => {
    router.push({
        path: './certificationDetail',
        query: { id: row.id }
    })
}
/** 取消按钮 */
const cancel = () => {
    reset();
    dialog.visible = false;
}
/** 表单重置 */
const reset = () => {
    form.value = { ...initFormData };
    postFormRef.value?.resetFields();
}
/** 搜索按钮操作 */
const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
}
/** 重置按钮操作 */
const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
}
/** 多选框选中数据 */
const handleSelectionChange = (selection) => {
    ids.value = selection.map(item => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}
/** 新增按钮操作 */
const handleAdd = () => {
    reset();
    dialog.visible = true;
    getCode()
    dialog.title = "添加资质信息";
}
/** 新增获取编号 */
const getCode = () => {
    code().then((res) => {
        if (res.code == 200) {
            form.value.certificateId = res.data
        } else {
            ElMessage({
                type: 'error',
                message: res.msg,
            })
        }
    })
}
const getCompanyName = () => {
    companyName().then((res) => {
        if (res.code == 200) {
            companyNameList.value = res.rows
        } else {
            ElMessage({
                type: 'error',
                message: res.msg,
            })
        }
    })
}
/** 修改按钮操作 */
const handleUpdate = async (row) => {
    reset();
    form.value.idArray = row?.id || ids.value[0];
    const res = await getDetail(form.value.idArray);
    Object.assign(form.value, res.data);
    dialog.visible = true;
    dialog.title = "修改资质信息";
}
/** 提交按钮 */
const submitForm = () => {
    postFormRef.value?.validate(async (valid) => {
        if (valid) {
            form.value.idArray ? await update(form.value) : await add(form.value);
            dialog.visible = false;
            ElMessage({
                type: 'success',
                message: '操作成功',
            })
            await getList();
        }
    });
}
/** 删除按钮操作 */
const handleDelete = async (row) => {
    ElMessageBox.confirm(
        '确定删除吗?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            const idArray = row?.id || ids.value;
            del(idArray).then(() => {
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                })
                getList();
            })
        })
        .catch(() => {
        })

}
/** 导出按钮操作 */
const handleExport = () => {
    proxy?.download("/system/companyCert/export", {
        ...queryParams.value
    }, `${pageName}${new Date().getTime()}.xlsx`);
}

onMounted(() => {
    getList();
    getCompanyName();
});
</script>